<script setup lang="ts">
import { useShowPrescription } from '@/composable'
import { deleteOrder } from '@/services/consult'
import type { ConsultOrderItem } from '@/types/consult'
import {
  showConfirmDialog,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
} from 'vant'
import { inject } from 'vue'
import { computed, ref } from 'vue'

const { onShowPrescription } = useShowPrescription()

const props = defineProps<{
  item: ConsultOrderItem
  delCb?: (item: ConsultOrderItem) => void
}>()

const showPopover = ref(false)
const actions = computed(() => [
  { text: '查看处方', disabled: !props.item.prescriptionId, type: 'preview' },
  { text: '删除订单', type: 'del' },
])

// 注入 ConsultList 组件的 onDel 方法
const onDelOfConsultList = inject<(id: string) => void>('onDel')

// 既然组件已经固定了行为，就直接在组件内部做了算了
// const emit = defineEmits<{
//   (e: 'on-delete'): void
//   (e: 'on-preview'): void
// }>()
// #region 删除订单
const delOrder = async (item: ConsultOrderItem) => {
  await showConfirmDialog({
    title: '温馨提示',
    message: '你确定要删除吗？',
  })

  // vant 同时只能存在一个 toast，后面弹出来的 toast 会自动关闭前面的 toast
  showLoadingToast({
    message: '订单删除中...',
    forbidClick: true,
  })

  try {
    // 1. 调API
    await deleteOrder(item.id)
    // 2. 通知父组件更新 list
    onDelOfConsultList && onDelOfConsultList(item.id)
    props.delCb && props.delCb(item)
    showSuccessToast('删除成功')
  } catch (err) {
    showFailToast('删除失败，请稍后重试！')
  }
}
// #endregion

const onSelect = (action: { text: string; type: string }) => {
  if (action.type === 'preview') {
    onShowPrescription(props.item.prescriptionId)
  } else if (action.type === 'del') {
    delOrder(props.item)
  }
}
</script>

<template>
  <div class="consult-more">
    <van-popover
      placement="top-start"
      v-model:show="showPopover"
      :actions="actions"
      @select="onSelect"
    >
      <template #reference> 更多 </template>
    </van-popover>
  </div>
</template>

<style lang="scss" scoped>
.consult-more {
  flex: 1;
  color: var(--cp-tag);
  font-size: 13px;
}
</style>
<!-- `` 使用组件：`User/components/ConsultItem.vue` ```html
<cp-consult-more
  :disabled="!item.prescriptionId"
  @on-delete="deleteConsultOrder(item)"
  @on-preview="onShowPrescription(item.prescriptionId)"
></cp-consult-more> -->
